<template>
  <el-splitter>
    <el-splitter-panel>
      <div>编辑区</div>
      <el-switch
        v-model="form.content_type"
        active-text="Markdown"
        :active-value="ArticleContentType.MARKDOWN"
        inactive-text="富文本"
        :inactive-value="ArticleContentType.HTML"
      />
      <div class="edit-box">
        <el-form
          :model="form"
          :rules="rules"
          ref="formRef"
          label-width="auto"
          label-position="top"
          style="margin-top: 16px"
        >
          <el-form-item label="标题" prop="title" required>
            <el-input v-model="form.title" placeholder="请输入文章标题" />
          </el-form-item>
          <el-form-item
            label="内容"
            prop="editorValue"
            v-if="form.content_type === ArticleContentType.HTML"
            required
          >
            <EditorComponent
              v-model="form.editorValue"
              @update:modelValue="onEditorChange"
            />
          </el-form-item>
          <el-form-item
            label="内容"
            prop="articleContent"
            v-if="form.content_type === ArticleContentType.MARKDOWN"
            required
          >
            <v-md-editor
              v-model="form.articleContent"
              @change="onEditorChange"
              height="500px"
              :preview="false"
              mode="edit"
            />
          </el-form-item>
          <el-form-item label="标签">
            <el-input-tag
              v-model="form.tags"
              placeholder="Please input"
              aria-label="Please click the Enter key after input"
            />
          </el-form-item>
          <el-form-item label="封面图">
            <up-load-img v-model="form.cover_image" action="/api/file/upload" />
          </el-form-item>
          <el-form-item label="摘要">
            <el-input v-model="form.desc" />
          </el-form-item>
          <el-form-item label="分类">
            <el-select v-model="form.category" placeholder="请选择分类">
              <el-option label="分类一" value="分类一" />
              <el-option label="分类二" value="分类二" />
            </el-select>
          </el-form-item>
          <el-form-item label="可见性设置">
            <el-select v-model="form.visible" placeholder="请选择">
              <el-option label="所有人可见" value="所有人可见" />
              <el-option label="仅VIP可见" value="仅VIP可见" />
              <el-option label="仅自己可见" value="仅自己可见" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="router.back()">取消</el-button>
            <el-button type="primary" @click="handleSave">{{
              mode === "edit" ? "保存修改" : "创建草稿"
            }}</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-splitter-panel>
    <el-splitter-panel>
      <div>预览区</div>
      <div class="preview-box">
        <div
          v-if="form.content_type === ArticleContentType.HTML"
          v-html="form.editorValue"
        />
        <v-md-editor
          v-else
          :model-value="form.articleContent"
          mode="preview"
          height="500px"
        />
      </div>
    </el-splitter-panel>
  </el-splitter>
</template>

<script setup lang="ts">
import { ref, watch, defineProps, defineEmits, reactive } from 'vue';
import EditorComponent from '@/components/common/EditorComponent.vue';
import { ArticleContentType } from '@/constant/article';
import UpLoadImg from '@/components/common/upLoadImg.vue';
import { useRouter } from 'vue-router';

const router = useRouter();
const props = defineProps<{ modelValue: any; mode: 'add' | 'edit' }>();
const emits = defineEmits(['update:modelValue', 'save']);

const form = reactive(
  props.modelValue ?? {
    title: '',
    tags: [],
    cover_image: '',
    category: '',
    desc: '',
    visible: '',
    editorValue: '',
    articleContent: '',
    content_type: ''
  }
);
const formRef = ref();
const rules = {
  title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
  editorValue: [
    {
      validator(_rule: any, value: string, callback: Function) {
        // 富文本内容去除 html 标签和空白再判断
        const val = value ? value.replace(/<[^>]+>/g, '').replace(/\s/g, '') : '';
        if (form.content_type === ArticleContentType.HTML && (!val || val.length === 0)) {
          callback(new Error('内容不能为空'));
        } else {
          callback();
        }
      },
      trigger: ['blur', 'change']
    }
  ],
  articleContent: [
    {
      validator(_rule: any, value: string, callback: Function) {
        if (
          form.content_type === ArticleContentType.MARKDOWN &&
          (!value || value.trim() === '')
        ) {
          callback(new Error('内容不能为空'));
        } else {
          callback();
        }
      },
      trigger: ['blur', 'change']
    }
  ]
};

function onEditorChange() {
  if (form.content_type === ArticleContentType.HTML) {
    formRef.value?.validateField('editorValue');
  } else if (form.content_type === ArticleContentType.MARKDOWN) {
    formRef.value?.validateField('articleContent');
  }
}

watch(
  () => props.modelValue,
  (val) => {
    if (val && JSON.stringify(val) !== JSON.stringify(form)) {
      Object.assign(form, val);
    }
  }
);
watch(
  form,
  (val) => {
    emits('update:modelValue', { ...val });
  },
  { deep: true }
);

function handleClick() {
  if (!form.editorValue && !form.articleContent) {
    alert('文章内容不能为空');
    return;
  }
  const content =
    form.content_type === ArticleContentType.MARKDOWN
      ? form.articleContent
      : form.editorValue;

  emits('save', {
    ...form,
    content
  });
}

function handleSave() {
  formRef.value?.validate((valid: boolean) => {
    if (!valid) return;
    handleClick();
  });
}
</script>

<style scoped>
.edit-box {
  margin-right: 16px;
}
.preview-box {
  border: 1px solid #ccc;
  height: calc(100vh - 300px);
  background: #fff;
  overflow-y: auto;
  padding: 16px;
  margin-left: 16px;
  margin-top: 32px;
}
</style>
